﻿using System;
using System.Linq;
using System.Threading.Tasks;
using General.Core.Data;
using General.Entities.Data;
using General.Entities.Models;
using Microsoft.EntityFrameworkCore;

namespace General.Services.SystemLogs
{
    public class SystemLogsService:ISystemLogsService
    {
        private readonly IRepository<tc_systemlogs> tc_SystemlogsRepository;

        public SystemLogsService(IRepository<tc_systemlogs> tc_systemlogsRepository)
        {
            tc_SystemlogsRepository = tc_systemlogsRepository;
        }



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public async Task<AdminResult> GetList(int page, int limit, string message, string exception, string level)
        {
            AdminResult result = new AdminResult();
            var query = from d in tc_SystemlogsRepository.Table
                        orderby d.id descending
                        select new tc_systemlogs()
                        {
                             Exception = d.Exception,
                              id = d.id , Level  =d.Level , Message = d.Message, Timestamp=d.Timestamp
                        };

            if (!string.IsNullOrWhiteSpace(message))
            {
                query = query.Where(x=>x.Message.Contains(message));
            }
            if (!string.IsNullOrWhiteSpace(exception))
            {
                query = query.Where(x => x.Exception.Contains(exception));
            }
            if (!string.IsNullOrWhiteSpace(level))
            {
                query = query.Where(x => x.Level==level);
            }
            result.count = await query.CountAsync();
            result.data = await query.Skip((page - 1) * limit).Take(limit).ToListAsync();
            result.code = 0;
            

            return result;
        }


        /// <summary>
        /// 删除所有数据
        /// </summary>
        /// <returns></returns>
        public async Task<int> DeleteAll()
        {
            var res = await tc_SystemlogsRepository.ExecuteSqlAsync("delete from tc_systemlogs");
            return res;
        }

        /// <summary>
        /// 删除指定id
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteByIds(string ids)
        {
            var arr = ids.Split(",",StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x));
            var list = await tc_SystemlogsRepository.GetAllAsync(x=>arr.Contains(x.id)).ToListAsync();
            return await tc_SystemlogsRepository.DeleteListAsync(list);
        }
    }
}
